﻿Imports System.Data.SqlClient
Imports Suprema

Public Class frmIngresoDiesel
    Private m_ScannerManager As UFScannerManager
    Private m_Scanner As UFScanner
    Private m_Matcher As UFMatcher
    Private m_Database As UFDatabase
    Private m_strError As String
    Private m_Serial As Integer
    Private m_UserID As String
    Private m_FingerIndex As Integer
    Private m_Template1 As Byte()
    Private m_Template1Size As Integer
    Private m_Template2 As Byte()
    Private m_Template2Size As Integer
    Private m_Memo As String
    '
    Private Const MAX_USERID_SIZE As Integer = 50
    Private Const MAX_TEMPLATE_SIZE As Integer = 1024
    Private Const MAX_MEMO_SIZE As Integer = 100
    '
    Private Const DATABASE_COL_SERIAL As Integer = 0
    Private Const DATABASE_COL_USERID As Integer = 1
    Private Const DATABASE_COL_FINGERINDEX As Integer = 2
    Private Const DATABASE_COL_TEMPLATE1 As Integer = 3
    Private Const DATABASE_COL_TEMPLATE2 As Integer = 4
    Private Const DATABASE_COL_MEMO As Integer = 5

    Private minuto As Integer = 0
    Private segundo As Integer = 0
    Private milisegundo As Integer = 0
    Private minutoM As Integer = 0
    Private segundoM As Integer = 0
    Private milisegundoM As Integer = 0
    Private Intentos As Integer = 0

    Private Sub frmIngresoDiesel_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Terminar()

    End Sub
    Private Sub frmIngresoDiesel_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'ToolStrip1.Cursor = Cursors.Hand
        'ToolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System

        m_ScannerManager = New UFScannerManager(Me)
        m_Scanner = Nothing
        m_Matcher = Nothing
        m_Database = Nothing

        m_Template1 = New Byte(MAX_TEMPLATE_SIZE) {}
        m_Template2 = New Byte(MAX_TEMPLATE_SIZE) {}
        tbxMessage.Clear()

        Iniciar()
        Intentos = 0
        Timer1.Enabled = True



    End Sub
    Sub Verificar()
        Dim ufd_res As UFD_STATUS
        Dim ufm_res As UFM_STATUS
        ' Input finger data
        Dim Template As Byte() = New Byte(MAX_TEMPLATE_SIZE) {}
        Dim TemplateSize As Integer
        ' DB data
        Dim DBTemplate As Byte()() = Nothing
        Dim DBTemplateSize As Integer() = Nothing
        Dim DBSerial As Integer() = Nothing
        Dim DBTemplateNum As Integer
        '
        Dim MatchIndex As Integer

        ufd_res = m_Database.GetTemplateListWithSerial(DBTemplate, DBTemplateSize, DBTemplateNum, DBSerial)
        If (ufd_res <> UFD_STATUS.OK) Then
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Obteniendo listado: " + m_strError + vbNewLine)
            Exit Sub
        End If

        If (Not ExtractTemplate(Template, TemplateSize)) Then
            Exit Sub
        End If

        DrawCapturedImage(m_Scanner)

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufm_res = m_Matcher.Identify(Template, TemplateSize, DBTemplate, DBTemplateSize, DBTemplateNum, 5000, MatchIndex)
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufm_res <> UFM_STATUS.OK) Then
            UFMatcher.GetErrorString(ufm_res, m_strError)
            tbxMessage.AppendText("Identificación: " & m_strError & vbNewLine)
            Exit Sub
        End If

        If (MatchIndex <> -1) Then
            'tbxMessage.AppendText("Identification succeed (Serial = " & DBSerial(MatchIndex) & ")" & vbNewLine)
            Dim Usuario As String = BuscarStrDatoBiometria("SELECT UserID FROM fingerprints WHERE Serial=" & DBSerial(MatchIndex))
            Dim Nombre As String = BuscarStrDatoInicial("SELECT NombreCompleto FROM Usuarios WHERE Nombre='" & Usuario & "'")
            tbxMessage.AppendText("Usuario identificado: " & Nombre & vbNewLine)
            Application.DoEvents()
            Dim IdUsuario As Integer = BuscarIntDatoInicial("SELECT IdUsuario FROM Usuarios WHERE Nombre='" & Usuario & "'")

            Dim idFormulario As String = BuscarIntDatoInicial("Formularios", "IdFormulario", "formulario='frmModuloDiesel'")
            Dim Permiso As Integer = BuscarIntDatoInicial("PermisosUsuarios", "Permiso", "IdUsuario=" & IdUsuario & " AND IdFormulario=" & idFormulario)
            If Permiso > 0 Then
                tbxMessage.AppendText("Acceso Permitido" & vbNewLine)
                'frmModuloDiesel.ShowDialog()
                IdEmpleado = BuscarIntDatoCitra("SELECT IdEmpleado FROM AsignacionBiometria WHERE NombreUsuario='" & Usuario & "'")
                frmMain.Timer2.Enabled = True
                Close()
            Else
                tbxMessage.AppendText("Acceso Denegado" & vbNewLine)
                Intentos = Intentos + 1
                If Intentos > 2 Then
                    Close()
                End If
            End If
        Else
            tbxMessage.AppendText("No se realizo la identificación" & vbNewLine)
            Intentos = Intentos + 1
            If Intentos > 2 Then
                Close()
            End If
        End If

       

    End Sub
    Sub Iniciar()
        '==========================================================================='
        ' Initilize scanners
        '==========================================================================='
        Dim ufs_res As UFS_STATUS
        Dim nScannerNumber As Integer

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Init()
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufs_res = UFS_STATUS.OK) Then
            tbxMessage.AppendText("Conexión del scanner: Correcta" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            tbxMessage.AppendText("Conexión del scanner: " & m_strError & vbNewLine)
            Exit Sub
        End If

        nScannerNumber = m_ScannerManager.Scanners.Count
        'tbxMessage.AppendText("UFScanner GetScannerNumber: " & nScannerNumber & vbNewLine)

        If (nScannerNumber = 0) Then
            tbxMessage.AppendText("No hay scanners disponibles" & vbNewLine)
            Exit Sub
        Else
            tbxMessage.AppendText("El primer scanner será usado" & vbNewLine)
        End If

        m_Scanner = m_ScannerManager.Scanners(0)
        '==========================================================================='

        '==========================================================================='
        ' Open database
        '==========================================================================='
        Dim ufd_res As UFD_STATUS

        m_Database = New UFDatabase()

        ' Generate connection string
        Dim DataSource As String
        Dim Connection As String
        '
        'DataSource = "UFDatabase.mdb"
        '
        'tbxMessage.AppendText("Select a database file" & vbNewLine)
        'Dim dlg As OpenFileDialog = New OpenFileDialog()
        'dlg.FileName = "UFDatabase.mdb"
        'dlg.Filter = "Database Files (*.mdb)|*.mdb"
        'dlg.DefaultExt = "mdb"
        'Dim res As DialogResult = dlg.ShowDialog()
        'If (res <> Windows.Forms.DialogResult.OK) Then
        'Exit Sub
        'End If

        DataSource = CitraInicial & "\UFDatabase.mdb"
        '
        Connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DataSource & ";"

        ' Open database
        ufd_res = m_Database.Open(Connection, "", "")
        If (ufd_res = UFD_STATUS.OK) Then
            tbxMessage.AppendText("Apertura de la base de datos: Correcta" & vbNewLine)
        Else
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Apertura de la base de datos: " & m_strError & vbNewLine)
            Exit Sub
        End If

        '==========================================================================='

        '==========================================================================='
        ' Create matcher
        '==========================================================================='
        m_Matcher = New UFMatcher()
        '==========================================================================='
    End Sub
    Sub Terminar()
        '==========================================================================='
        ' Uninit scanner module
        '==========================================================================='
        Dim ufs_res As UFS_STATUS

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Uninit()
        Windows.Forms.Cursor.Current = Me.Cursor

        If (ufs_res = UFS_STATUS.OK) Then
            tbxMessage.AppendText("UFScanner Uninit: OK" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            tbxMessage.AppendText("UFScanner Uninit: " & m_strError & vbNewLine)
        End If
        '==========================================================================='

        '==========================================================================='
        ' Close database
        '==========================================================================='
        If (Not Equals(m_Database, Nothing)) Then
            Dim ufd_res As UFD_STATUS

            ' Close database
            ufd_res = m_Database.Close()
            If (ufd_res = UFD_STATUS.OK) Then
                tbxMessage.AppendText("Cierre de Base de datos: OK" & vbNewLine)
            Else
                UFDatabase.GetErrorString(ufd_res, m_strError)
                tbxMessage.AppendText("Cierre de Base de datos: " & m_strError & vbNewLine)
            End If
        End If

        'lvDatabaseList.Items.Clear()
    End Sub
    Private Function ExtractTemplate(ByRef Template As Byte(), ByRef TemplateSize As Integer) As Boolean
        Dim ufs_res As UFS_STATUS
        Dim EnrollQuality As Integer

        m_Scanner.ClearCaptureImageBuffer()

        tbxMessage.AppendText("Colocar dedo índice" & vbNewLine)

        TemplateSize = 0
        Do
            ufs_res = m_Scanner.CaptureSingleImage()
            If (ufs_res <> UFS_STATUS.OK) Then
                UFScanner.GetErrorString(ufs_res, m_strError)
                tbxMessage.AppendText("Capturando imágen: " & m_strError & vbNewLine)
                ExtractTemplate = False
                Exit Function
            End If

            DrawCapturedImage(m_Scanner)

            ufs_res = m_Scanner.Extract(Template, TemplateSize, EnrollQuality)
            If (ufs_res = UFS_STATUS.OK) Then
                tbxMessage.AppendText("Extracción de imagen: OK" & vbNewLine)
                Exit Do
            Else
                UFScanner.GetErrorString(ufs_res, m_strError)
                tbxMessage.AppendText("Extracción de imagen: " & m_strError & vbNewLine)
            End If
        Loop

        ExtractTemplate = True
    End Function
    Private Sub DrawCapturedImage(ByRef Scanner As UFScanner)
        Dim g As Graphics = pbImageFrame.CreateGraphics()
        Dim rect As Rectangle = New Rectangle(0, 0, pbImageFrame.Width, pbImageFrame.Height)
        Dim Resolution As Integer
        Try
            '
            'Scanner.DrawCaptureImageBuffer(g, rect, cbDetectCore.Checked);
            '
            Dim bitmap As Bitmap = Nothing
            Scanner.GetCaptureImageBuffer(bitmap, Resolution)
            pbImageFrame.Image = bitmap
        Finally
            g.Dispose()
        End Try
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        milisegundo += 1
        If milisegundo = 9 Then
            milisegundo = 0
            segundo += 1

            If segundo = 1 Then
                Verificar()
                Timer1.Enabled = False

            End If
        End If
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        Verificar()

    End Sub
End Class